<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的收藏 - Shioa</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/main.css">
</head>

<body class="bg-gradient-to-br from-blue-50 via-white to-indigo-50 min-h-screen">
    <!-- Toast 消息容器 -->
    <div id="toast-container" class="toast-container space-y-2"></div>

    <!-- 导航由 shared-navigation.js 统一管理，实现真正的组件复用 -->

    <!-- 面包屑导航 -->
    <div class="max-w-[1440px] mx-auto px-6 py-4">
        <nav class="flex items-center gap-2 text-sm text-gray-500">
            <a href="/" class="hover:text-primary-600 transition-colors">
                <i class="fas fa-home"></i>
            </a>
            <span class="mx-2">/</span>
            <span class="text-gray-700">我的收藏</span>
        </nav>
    </div>

    <!-- 页面主内容 -->
    <div class="max-w-[1440px] mx-auto px-6 pb-12">
        <!-- 筛选和排序控制 -->
        <div class="bg-white rounded-lg shadow-sm border mb-6">
            <div class="p-4">
                <div class="flex items-center justify-between flex-wrap gap-4">
                    <div class="flex items-center gap-6">
                        <!-- 统计信息 -->
                        <div class="flex items-center gap-2">
                            <span class="text-sm text-gray-500">收藏总数:</span>
                            <span class="text-lg font-semibold text-gray-900" id="total-favorites">0</span>
                        </div>
                        <!-- 排序选择 -->
                        <div class="flex items-center gap-2">
                            <label class="text-sm font-medium text-gray-700">排序方式:</label>
                            <select id="sort-select" class="border border-gray-300 rounded-md px-3 py-1 text-sm" onchange="changeSorting()">
                                <option value="favorited_at,desc">收藏时间 (最新)</option>
                                <option value="favorited_at,asc">收藏时间 (最早)</option>
                                <option value="hot_score,desc">热度评分 (高到低)</option>
                                <option value="hot_score,asc">热度评分 (低到高)</option>
                                <option value="view_count,desc">播放量 (高到低)</option>
                                <option value="view_count,asc">播放量 (低到高)</option>
                            </select>
                        </div>
                    </div>
                    <div class="flex items-center gap-3">
                        <!-- 刷新按钮 -->
                        <button onclick="refreshFavorites()" class="px-4 py-2 bg-blue-50 text-blue-600 hover:bg-blue-100 rounded-lg transition-colors">
                            <i class="fas fa-refresh mr-2"></i>刷新
                        </button>
                        <!-- 清空收藏按钮 -->
                        <button onclick="clearAllFavorites()" class="px-4 py-2 text-red-600 hover:bg-red-50 rounded-lg border border-red-200 transition-colors">
                            <i class="fas fa-trash mr-2"></i>清空收藏
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 收藏视频列表 -->
        <div id="favorites-container">
            <!-- 加载状态 -->
            <div id="loading-state" class="text-center py-12">
                <i class="fas fa-spinner fa-spin text-2xl text-gray-400 mb-4"></i>
                <p class="text-gray-500">正在加载收藏视频...</p>
            </div>

            <!-- 空状态 -->
            <div id="empty-state" class="text-center py-12 hidden">
                <i class="fas fa-heart text-4xl text-gray-300 mb-4"></i>
                <h3 class="text-lg font-medium text-gray-900 mb-2">还没有收藏任何视频</h3>
                <p class="text-gray-500 mb-6">去 <a href="trending.html" class="text-blue-600 hover:underline">爆款视频</a> 或 <a href="videos.html" class="text-blue-600 hover:underline">视频管理</a> 页面收藏喜欢的视频吧！</p>
            </div>

            <!-- 视频列表 -->
            <div id="favorites-list" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                <!-- 视频卡片将通过 JavaScript 动态插入 -->
            </div>
        </div>

        <!-- 分页控件 -->
        <div id="pagination-container" class="mt-8 flex justify-center">
            <!-- 分页按钮将通过 JavaScript 动态生成 -->
        </div>
    </div>

    <!-- JavaScript -->
    <!-- JavaScript -->
    <script src="js/env.js"></script>
    <script>
    // 设置全局API配置
    window.API_BASE_URL = API_BASE_URL;
    </script>
    <script src="js/config.js"></script>
    <script src="js/utils.js"></script>
    <script src="js/api.js"></script>
    <script>
        // 收藏页面管理类
        class FavoritesManager {
            constructor() {
                this.currentPage = 1;
                this.perPage = 20;
                this.currentSort = 'favorited_at';
                this.currentOrder = 'desc';
                this.totalFavorites = 0;
                this.init();
            }

            async init() {
                console.log('🎬 [收藏] 收藏页面管理器初始化...');
                
                // 检查认证状态
                const isAuthenticated = await this.checkAuth();
                if (!isAuthenticated) {
                    console.log('❌ [收藏] 用户未认证，重定向到登录页');
                    window.location.href = 'login.html';
                    return;
                }

                // 加载收藏列表
                await this.loadFavorites();
                
                // 加载统计信息
                await this.loadStats();
                
                console.log('✅ [收藏] 收藏页面管理器初始化完成');
            }

            async checkAuth() {
                try {
                    const token = localStorage.getItem('access_token');
                    if (!token) {
                        return false;
                    }
                    
                    const response = await api.verifyToken();
                    return response && response.success;
                } catch (error) {
                    console.error('认证检查失败:', error);
                    return false;
                }
            }

            async loadFavorites() {
                try {
                    this.showLoading();
                    
                    const response = await api.getFavorites({
                        page: this.currentPage,
                        per_page: this.perPage,
                        order_by: this.currentSort,
                        order: this.currentOrder
                    });
                    
                    if (response.success) {
                        this.renderFavorites(response.data.favorites);
                        this.renderPagination(response.data.pagination);
                        this.totalFavorites = response.data.pagination.total;
                        
                        if (response.data.favorites.length === 0 && this.currentPage === 1) {
                            this.showEmptyState();
                        }
                    } else {
                        throw new Error(response.message || '获取收藏失败');
                    }
                } catch (error) {
                    console.error('加载收藏失败:', error);
                    showToast('加载收藏失败: ' + error.message, 'error');
                    this.showEmptyState();
                }
            }

            async loadStats() {
                try {
                    const response = await api.getFavoriteStats();
                    if (response.success) {
                        document.getElementById('total-favorites').textContent = response.data.total_count;
                    }
                } catch (error) {
                    console.error('加载统计信息失败:', error);
                }
            }

            renderFavorites(favorites) {
                const container = document.getElementById('favorites-list');
                const loadingState = document.getElementById('loading-state');
                const emptyState = document.getElementById('empty-state');
                
                loadingState.classList.add('hidden');
                emptyState.classList.add('hidden');
                
                if (favorites.length === 0) {
                    this.showEmptyState();
                    return;
                }
                
                container.innerHTML = favorites.map(favorite => this.createVideoCard(favorite)).join('');
            }

            createVideoCard(favorite) {
                const publishedDate = favorite.published_at ? new Date(favorite.published_at).toLocaleDateString() : '未知';
                const favoritedDate = favorite.favorited_at ? new Date(favorite.favorited_at).toLocaleDateString() : '未知';
                
                return `
                    <div class="bg-white rounded-lg shadow-sm border hover:shadow-md transition-shadow">
                        <div class="aspect-video bg-gray-100 rounded-t-lg overflow-hidden">
                            <img src="${favorite.thumbnail_url || '/assets/images/video-placeholder.jpg'}" 
                                 alt="${favorite.title}" 
                                 class="w-full h-full object-cover"
                                 onerror="this.src='/assets/images/video-placeholder.jpg'">
                        </div>
                        <div class="p-4">
                            <h3 class="font-medium text-gray-900 mb-2 line-clamp-2">${favorite.title}</h3>
                            <p class="text-sm text-gray-600 mb-2">${favorite.channel_title}</p>
                            <div class="flex items-center gap-4 text-xs text-gray-500 mb-3">
                                <span><i class="fas fa-eye mr-1"></i>${Utils.formatNumber(favorite.view_count)}</span>
                                <span><i class="fas fa-thumbs-up mr-1"></i>${Utils.formatNumber(favorite.like_count)}</span>
                                <span><i class="fas fa-fire mr-1"></i>${favorite.hot_score.toFixed(1)}</span>
                            </div>
                            <div class="flex items-center justify-between">
                                <div class="text-xs text-gray-400">
                                    <div>发布: ${publishedDate}</div>
                                    <div>收藏: ${favoritedDate}</div>
                                </div>
                                <div class="flex items-center gap-2">
                                    <button onclick="window.open('https://www.youtube.com/watch?v=${favorite.video_id}', '_blank')" 
                                            class="px-3 py-1 text-xs bg-red-50 text-red-600 hover:bg-red-100 rounded-md transition-colors">
                                        观看
                                    </button>
                                    <button onclick="favoritesManager.removeFavorite('${favorite.video_id}')" 
                                            class="px-3 py-1 text-xs bg-gray-50 text-gray-600 hover:bg-gray-100 rounded-md transition-colors">
                                        移除
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            }

            renderPagination(pagination) {
                const container = document.getElementById('pagination-container');
                if (pagination.pages <= 1) {
                    container.innerHTML = '';
                    return;
                }

                let html = '<div class="flex items-center gap-2">';
                
                // 上一页
                if (pagination.has_prev) {
                    html += `<button onclick="favoritesManager.goToPage(${pagination.page - 1})" class="px-3 py-2 text-sm border border-gray-300 rounded-md hover:bg-gray-50">上一页</button>`;
                }
                
                // 页码
                for (let i = Math.max(1, pagination.page - 2); i <= Math.min(pagination.pages, pagination.page + 2); i++) {
                    if (i === pagination.page) {
                        html += `<button class="px-3 py-2 text-sm bg-blue-600 text-white rounded-md">${i}</button>`;
                    } else {
                        html += `<button onclick="favoritesManager.goToPage(${i})" class="px-3 py-2 text-sm border border-gray-300 rounded-md hover:bg-gray-50">${i}</button>`;
                    }
                }
                
                // 下一页
                if (pagination.has_next) {
                    html += `<button onclick="favoritesManager.goToPage(${pagination.page + 1})" class="px-3 py-2 text-sm border border-gray-300 rounded-md hover:bg-gray-50">下一页</button>`;
                }
                
                html += '</div>';
                container.innerHTML = html;
            }

            async goToPage(page) {
                this.currentPage = page;
                await this.loadFavorites();
            }

            async removeFavorite(videoId) {
                if (!confirm('确定要移除这个收藏吗？')) {
                    return;
                }
                
                try {
                    const response = await api.removeFavorite(videoId);
                    if (response.success) {
                        showToast('已移除收藏', 'success');
                        await this.loadFavorites();
                        await this.loadStats();
                    } else {
                        throw new Error(response.message || '移除收藏失败');
                    }
                } catch (error) {
                    console.error('移除收藏失败:', error);
                    showToast('移除收藏失败: ' + error.message, 'error');
                }
            }

            showLoading() {
                document.getElementById('loading-state').classList.remove('hidden');
                document.getElementById('empty-state').classList.add('hidden');
                document.getElementById('favorites-list').innerHTML = '';
            }

            showEmptyState() {
                document.getElementById('loading-state').classList.add('hidden');
                document.getElementById('empty-state').classList.remove('hidden');
                document.getElementById('favorites-list').innerHTML = '';
            }
        }

        // 全局函数
        function changeSorting() {
            const sortSelect = document.getElementById('sort-select');
            const [orderBy, order] = sortSelect.value.split(',');
            favoritesManager.currentSort = orderBy;
            favoritesManager.currentOrder = order;
            favoritesManager.currentPage = 1;
            favoritesManager.loadFavorites();
        }

        function refreshFavorites() {
            favoritesManager.loadFavorites();
            favoritesManager.loadStats();
        }

        async function clearAllFavorites() {
            if (!confirm('确定要清空所有收藏吗？此操作不可撤销！')) {
                return;
            }
            
            try {
                const response = await api.clearAllFavorites();
                if (response.success) {
                    showToast(`已清空所有收藏 (${response.data.deleted_count}个)`, 'success');
                    await favoritesManager.loadFavorites();
                    await favoritesManager.loadStats();
                } else {
                    throw new Error(response.message || '清空收藏失败');
                }
            } catch (error) {
                console.error('清空收藏失败:', error);
                showToast('清空收藏失败: ' + error.message, 'error');
            }
        }

        async function logout() {
            try {
                await api.logout();
                localStorage.removeItem('access_token');
                showToast('已退出登录', 'success');
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 1000);
            } catch (error) {
                console.error('退出登录失败:', error);
                localStorage.removeItem('access_token');
                window.location.href = 'login.html';
            }
        }

        // 初始化
        let favoritesManager;
        document.addEventListener('DOMContentLoaded', () => {
            favoritesManager = new FavoritesManager();
        });
    </script>
    <script src="js/shared-navigation.js"></script>
</body>
</html>